﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace hzGis.utils
{
    public class DBHelper
    {
        private static MySqlConnection msc;
        /// <summary>
        /// 验证数据库配置是否正常
        /// </summary>
        /// <param name="dbUrl"></param>
        /// <param name="dbUser"></param>
        /// <param name="dbPwd"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public static bool checkConnection(string dbUrl, string dbUser, string dbPwd, string dbName, string dbPort)
        {
            string connectionStr = "data source = " + dbUrl + "; port = " + dbPort + "; database = " + dbName + "; user = " + dbUser + "; password = " + dbPwd + "; charset = utf8;";
            MySqlConnection msc = new MySqlConnection(connectionStr);
            bool res = false;
            try
            {
                msc.Open();
                if (msc.State == System.Data.ConnectionState.Open)
                {
                    res = true;
                }
            }
            catch (Exception e)
            {
               
            }
            finally
            {
                try
                {
                    if (msc != null) { msc.Close(); }
                 }
                catch (Exception e2) { }
            }
            return res;
        }

        public static MySqlConnection getConnection(string dbUrl, string dbUser, string dbPwd, string dbName, string dbPort)
        {
            string connectionStr = "data source = " + dbUrl + "; port = " + dbPort + "; database = " + dbName + "; user = " + dbUser + "; password = " + dbPwd + "; charset = utf8;";
            if (msc != null)
            {
                return msc;
            }
            else
            {
                msc = new MySqlConnection(connectionStr);
                try
                {
                    msc.Open();
                    if (msc.State != System.Data.ConnectionState.Open)
                    {
                        msc = null;
                    }
                }
                catch (Exception e)
                {
                    msc = null;
                }
                return msc;
            }
        }
    }
}
